from typing import Union
from sqlalchemy.orm import Session
from .. import models, schemas
from .. import dependencies


def get_user(db: Session, user_id: int) -> Union[models.Users, None]:
    return db.query(models.Users).filter(models.Users.id == user_id).first()


def get_user_by_number(db: Session, user_number: str) -> Union[models.Users, None]:
    return db.query(models.Users).filter(models.Users.number == user_number).first()


def get_users(db: Session, limit: int, offset: int) -> list[models.Users]:
    return db.query(models.Users).offset(offset).limit(limit).all()


# 用户更新基本信息 返回更新后的信息
def update_user(db: Session, user: schemas.User_Update,
                current_user: schemas.Users) -> models.Users:
    db_user = get_user_by_number(db, current_user.number)
    if user.name:
        db_user.name = user.name
    if user.password:
        db_user.password = dependencies.hash_password(password=user.password)
    if user.sex:
        db_user.sex = user.sex
    db.commit()
    db.refresh(db_user)
    return db_user


def create_user(db: Session, user: schemas.Users_Create) -> models.Users:
    fake_hashed_password = dependencies.hash_password(password=user.password)
    db_user = models.Users(
        password=fake_hashed_password,
        number=user.number,
        name=user.name,
        sex=user.sex,
        enabled=1)

    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
